package com.gxc.recursion;

import java.util.ArrayList;
import java.util.List;

/**
 * 字符串的全部排列
 */
public class Permutation {

    public static void main(String[] args) {
        String str = "aabc";
        List<String> list = new ArrayList<>();
        permutation(str.toCharArray(), 0, list);
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("---------");

        permutation(str.toCharArray(), 0);
    }

    /**
     * 不使用额外空间
     * @param chars
     * @param i
     */
    private static void permutation(char[] chars, int i) {
        if (i == chars.length) {
            System.out.println(String.valueOf(chars));
            return;
        }
        boolean[] visit = new boolean[26];
        for (int j = i; j < chars.length; j++) {
            if (!visit[chars[j] - 'a']) {
                visit[chars[j] - 'a'] = true;
                swap(chars, i, j);
                permutation(chars, i+1);
                //还原
                swap(chars, i, j);
            }
        }
    }

    /**
     *
     * @param chars  字符串的字符数组
     * @param list   最后的结果
     */
    private static void permutation(char[] chars, int i, List<String> list) {
        if (i == chars.length) {
            list.add(String.valueOf(chars));
            return;
        }
        boolean[] visit = new boolean[26];
        for (int j = i; j < chars.length; j++) {
            if (!visit[chars[j] - 'a']) {
                visit[chars[j]  - 'a' ] = true;
                swap(chars, i, j);
                permutation(chars, i + 1, list);
                //还原
                swap(chars, i, j);
            }
        }
    }

    /**
     * 交换i和j的字符
     * @param chars
     * @param i
     * @param j
     */
    private static void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}
